﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;

namespace Odyssey.Interactivity
{
    public class BackAndNavigateToPageAction : TargetedTriggerAction<FrameworkElement>
    {
        public string TargetPage { get; set; }

        protected override void Invoke(object parameter)
        {
            var rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
            if (rootFrame != null)
            {
                rootFrame.Navigated += new System.Windows.Navigation.NavigatedEventHandler(rootFrame_Navigated);
                rootFrame.GoBack();
            }
        }

        void rootFrame_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            var rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;
            rootFrame.Navigated -= rootFrame_Navigated;

            PhoneApplicationPage page = e.Content as PhoneApplicationPage;
            rootFrame.Dispatcher.BeginInvoke(delegate
            {
                rootFrame.Navigate(new Uri(TargetPage, UriKind.Relative));
            });
        }
    }
}
